/**
 * ARB (Application Resource Bundle) 格式生成器
 * 适用于 Flutter 应用
 */
class ArbGenerator {
  static async generate(data, platform = "flutter") {
    if (!data || typeof data !== "object") {
      throw new Error("数据必须是一个对象");
    }

    // 默认使用支持占位符的生成方式
    return this.generateWithPlaceholders(data, platform);
  }

  static generateWithPlaceholders(data, platform = "flutter") {
    // 支持占位符的ARB格式
    const arbData = {};

    // 添加元数据
    arbData["@@locale"] = "en";
    arbData["@@last_modified"] = new Date().toISOString();
    arbData["@@generated_by"] = "i18n-CLI";

    const sortedKeys = Object.keys(data).sort();

    for (const key of sortedKeys) {
      let value = data[key];

      // 检测占位符模式 {variable}
      const placeholders = this.extractPlaceholders(value);

      arbData[key] = value;

      // 如果有占位符，添加占位符元数据
      if (placeholders.length > 0) {
        const metadata = {
          type: "text",
          description: `Translation for ${key}`,
          placeholders: {},
        };

        placeholders.forEach((placeholder) => {
          metadata.placeholders[placeholder] = {
            type: "String",
            description: `Placeholder for ${placeholder}`,
          };
        });

        arbData[`@${key}`] = metadata;
      } else {
        arbData[`@${key}`] = {
          type: "text",
          description: `Translation for ${key}`,
        };
      }
    }

    return JSON.stringify(arbData, null, 2);
  }

  static extractPlaceholders(text) {
    if (typeof text !== "string") {
      return [];
    }

    const placeholderRegex = /\{(\w+)\}/g;
    const placeholders = [];
    let match;

    while ((match = placeholderRegex.exec(text)) !== null) {
      placeholders.push(match[1]);
    }

    return [...new Set(placeholders)]; // 去重
  }

  static generateMetadata(locale = "en") {
    return {
      "@@locale": locale,
      "@@last_modified": new Date().toISOString(),
      "@@generated_by": "i18n-CLI",
      "@@version": "1.0.0",
    };
  }
}

module.exports = ArbGenerator;
